package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.service.FarmStockService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.JsonUtil;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsRetailProductionMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsRetailProduction;
import com.dongjiantong.farmrecords.service.FarmRecordsRetailProductionService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Lee
 * @date 2018/1/14
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsRetailProductionServiceImpl extends ServiceMybatis<FarmRecordsRetailProduction> implements FarmRecordsRetailProductionService {
    @Resource
    private FarmRecordsRetailProductionMapper farmrecordsRetailProductionMapper;

    @Reference(version = "1.0.0")
    private FarmStockService farmStockService;

    @Override
    public PageInfo<FarmRecordsRetailProduction> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        try {
            if (farmrecordsRetailProductionMapper == null){
                throw new OPServerException("farmrecordsRetailProductionMapper 为null,请检查");
            }
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());

            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsRetailProduction> list = farmrecordsRetailProductionMapper.selectByMap(map);
            /*if (list.size() > 0){
                this.setPicOrVideoList(list);
            }*/
            return new PageInfo<FarmRecordsRetailProduction>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public PageInfo<FarmRecordsRetailProduction> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        try{
            PageHelper.startPage(pageNum,pageSize);

            Map<String,Object> map = Maps.newHashMap();
            if (status != null){
                map.put("status",status);
            }
            map.put("farm_id",farmId);

            map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

            List<FarmRecordsRetailProduction> farmRecordsRetailProductionList = farmrecordsRetailProductionMapper.selectListByStatus(map);

            return new PageInfo<FarmRecordsRetailProduction>(farmRecordsRetailProductionList);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public Long createOne(LoginInfo loginInfo, FarmRecordsRetailProduction farmRecordsRetailProduction, Integer toStatus, Integer isFrom) {
        Long receiptId = 0L; //生产记录id
        try {
            if (farmrecordsRetailProductionMapper == null){
                throw new OPServerException("farmrecordsRetailProductionMapper 为null,请检查");
            }
            //操作前的数据
            String jsonBefore = JsonUtil.toJsonString(farmRecordsRetailProduction);

            Integer fromStatus = farmRecordsRetailProduction.getStatus();

            //todo 生成单据号
            //单据生成规则暂未定(此处为测试)
            String prefix = "RSC";
            prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
            String maxNumber = farmrecordsRetailProductionMapper.findMaxNumber(prefix);
            String number = ReportNumberMakerUtil.create(prefix,maxNumber);
            farmRecordsRetailProduction.setNumber(number);

            //地区信息
            farmRecordsRetailProduction.setProvince_id(loginInfo.getProvinceId());
            farmRecordsRetailProduction.setCity_id(loginInfo.getCityId());
            farmRecordsRetailProduction.setRegion_id(loginInfo.getRegionId());
            farmRecordsRetailProduction.setStreet_id(loginInfo.getStreetId());
            farmRecordsRetailProduction.setVillage_id(loginInfo.getVillageId());

            //创建单据信息默认有效
            farmRecordsRetailProduction.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

            //todo 根据单据状态区分暂存提交
            if (fromStatus == 0 && toStatus == null){
                //直接暂存
                farmrecordsRetailProductionMapper.createOne(farmRecordsRetailProduction);
            }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)){
                //直接提交
                farmRecordsRetailProduction.setStatus(toStatus);
                farmrecordsRetailProductionMapper.createOne(farmRecordsRetailProduction);
                //todo 更改存栏量
                Map<String,Object> map = Maps.newHashMap();
                map.put("farmId",farmRecordsRetailProduction.getFarm_id());
                map.put("changeQuantity",farmRecordsRetailProduction.getChange_quantity());
                farmStockService.updateByFarmId(map);

                if (farmRecordsRetailProduction.getId() != null && farmRecordsRetailProduction.getId() != 0) {
                    receiptId = farmRecordsRetailProduction.getId();
                }
            }

            /*//todo 生成政府操作记录
           //操作后的数据
            String jsonAfter = JsonUtil.toJsonString(farmRecordsProduction);
            sysLogsService.createLogs(LogsEnum.ADD,
                    FarmRecordsTableEnum.FARM_RECORDS_PRODUCTION.getTableName(),
                    farmRecordsProduction.getId().toString(),
                    jsonBefore,
                    jsonAfter,
                    loginInfo.getId());*/

            return receiptId;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public Integer updateByIdOrNumber(FarmRecordsRetailProduction farmRecordsRetailProduction, Integer toStatus) {
        try {
            if (farmrecordsRetailProductionMapper == null){
                throw new OPServerException("farmrecordsRetailProductionMapper 为null,请检查");
            }

            //获取登录人
            Long userId = UserUtil.getUserId();
            //操作前的数据
            String jsonBefore = JsonUtil.toJsonString(farmRecordsRetailProduction);

            //todo 更新记录
            farmRecordsRetailProduction.setUpdated_at(new Date());
            farmRecordsRetailProduction.setStatus(toStatus);
            Integer con = farmrecordsRetailProductionMapper.updateByPrimaryKeySelective(farmRecordsRetailProduction);

            //2. 更改存栏量
            Map<String,Object> map = Maps.newHashMap();
            map.put("farmId",farmRecordsRetailProduction.getFarm_id());
            map.put("changeQuantity",farmRecordsRetailProduction.getChange_quantity());
            farmStockService.updateByFarmId(map);

            /*//todo 生成政府操作记录
            //操作后的数据
            String jsonAfter = JsonUtil.toJsonString(farmRecordsProduction);
            sysLogsService.createLogs(LogsEnum.UPDATE,
                    FarmRecordsTableEnum.FARM_RECORDS_PRODUCTION.getTableName(),
                    farmRecordsProduction.getId().toString(),
                    jsonBefore,
                    jsonAfter,
                    userId);*/

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    private Boolean deleteById(Long id) {
        FarmRecordsRetailProduction production = farmrecordsRetailProductionMapper.selectByPrimaryKey(id);
        //操作前的数据
        String jsonBefore = JsonUtil.toJsonString(production);
        //获取登陆人
        Long userId = UserUtil.getUserId();

        FarmRecordsRetailProduction farmRecordsRetailProduction = new FarmRecordsRetailProduction();
        farmRecordsRetailProduction.setId(id);
        farmRecordsRetailProduction.setDelete_flag(FarmRecordsNumberStatus.INVALID.getCode());
        farmRecordsRetailProduction.setUpdated_at(new Date());
        Integer con = farmrecordsRetailProductionMapper.updateByPrimaryKeySelective(farmRecordsRetailProduction);

        //todo 更改存栏信息
        Map<String,Object> map = Maps.newHashMap();
        map.put("farmId",production.getFarm_id());
        //还原单据之前对存栏变动数和实时存栏数量的改动
        map.put("changeQuantity",0 - production.getChange_quantity());
        farmStockService.updateByFarmId(map);

        /*//todo 生成政府操作记录
        //操作后的数据
        String jsonAfter = JsonUtil.toJsonString(farmRecordsProduction);
        sysLogsService.createLogs(LogsEnum.DELETE,
                FarmRecordsTableEnum.FARM_RECORDS_PRODUCTION.getTableName(),
                farmRecordsProduction.getId().toString(),
                jsonBefore,
                jsonAfter,
                userId);*/

        return con == 0 ? false : true;
    }

    /**
     * (政府端)
     * 根据养殖场id 动物畜种查询存栏变动数合计
     * @param farmId
     * @param breedSecondType
     */
    @Override
    public Integer selectQuantityChangeByFarmId(Long farmId, Integer breedSecondType) {
        Map<String,Object> map = Maps.newHashMap();

        map.put("farm_id",farmId);
        map.put("status",FarmRecordsNumberStatus.SUBMIT.getCode());
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        if (breedSecondType != null){
            map.put("breed_second_type",breedSecondType);
        }

        Integer changeQuantity = farmrecordsRetailProductionMapper.selectQuantityChangeByFarmId(map);

        return changeQuantity;
    }

    @Override
    public Integer selectQuantityChangeByGovAndBreedType(Long userId, Integer breedSecondType) {
        Map<String,Object> map = Maps.newHashMap();

        map.put("userId",userId);
        map.put("status",FarmRecordsNumberStatus.SUBMIT.getCode());
        map.put("deleteFlag",FarmRecordsNumberStatus.EFFECTIVE.getCode());
        map.put("breedSecondType",breedSecondType);

        Integer quantity = farmrecordsRetailProductionMapper.selectQuantityChangeByGovAndBreedType(map);

        if (quantity == null) {
            quantity = 0;
        }
        return quantity;
    }
}
